package com.the_ring.chapter06;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.the_ring.chapter06.bean.GoodsInfo;
import com.the_ring.chapter06.databse.DatabaseHelper;

public class ShoppingDetailActivity extends AppCompatActivity {

    private ImageView backIv;
    private TextView titleTv;
    private ImageView cartIv;
    private TextView countTv;
    private ImageView phoneIv;
    private TextView priceTv;
    private TextView detailTv;
    private Button saveToCartBt;

    private long rowId;

    private GoodsInfo info;
    private int cartCount;

    private DatabaseHelper helper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shopping_detail);

        rowId = getIntent().getLongExtra("goods_id", -1);

        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        helper = DatabaseHelper.getInstance(this);
        helper.openWriteLink();

        initData();
    }

    @Override
    protected void onPause() {
        super.onPause();
        helper.closeLink();
    }

    private void initView() {
        backIv = findViewById(R.id.iv_back);
        titleTv = findViewById(R.id.tv_title);
        cartIv = findViewById(R.id.iv_shop);
        countTv = findViewById(R.id.tv_count);
        priceTv = findViewById(R.id.tv_count);
        phoneIv = findViewById(R.id.iv_phone);
        priceTv = findViewById(R.id.tv_price);
        detailTv = findViewById(R.id.tv_detail);
        saveToCartBt = findViewById(R.id.bt_add_cart);

        backIv.setOnClickListener(v -> finish());
        cartIv.setOnClickListener(v -> {
            Intent intent = new Intent(ShoppingDetailActivity.this, ShoppingChannelActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        });
        saveToCartBt.setOnClickListener(v -> {
            helper.insertToCart(rowId);
            cartCount++;
            countTv.setText(String.valueOf(cartCount));
        });
    }

    public void initData() {
        info = helper.queryById(rowId);
        cartCount = helper.countOfCart();

        titleTv.setText(info.name);
        countTv.setText(String.valueOf(cartCount));
        phoneIv.setImageURI(Uri.parse(info.picPath));
        priceTv.setText(String.valueOf(info.price));
        detailTv.setText(info.detail);
    }
}